import pathlib
import time
import re
import typing
import os
import yaml
import ctypes
import psutil
import subprocess
import requests
import winsound
import datetime
import uiautomation
import win32gui
import rich
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *




def print_with_time(*args, **kwargs):
    """在输出内容前添加当前时间戳，使用rich.print进行格式化输出
    
    功能：在所有输出内容前自动添加当前本地时间，时间格式为YYYY-MM-DD HH:MM:SS
    时间会以蓝色加粗样式显示，其余内容保持rich的默认格式化特性
    
    Args:
        *args: 任意数量的位置参数，将被原样传递给rich.print
        **kwargs: 任意关键字参数，将被原样传递给rich.print
    
    Example:
        >>> print_with_time("系统启动完成")
        [bold blue][2025-08-07 16:45:30][/bold blue] 系统启动完成
        
        >>> print_with_time("操作结果：", "[green]成功[/green]")
        [bold blue][2025-08-07 16:46:10][/bold blue] 操作结果：[green]成功[/green]
    """
    # 获取当前时间并格式化为字符串
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # 拼接时间前缀与输出内容并打印
    rich.print(f"[bold blue][{current_time}][/bold blue]", *args, **kwargs)



def close_edge_open_dialog():
    start_time = datetime.datetime.now()
    while start_time + datetime.timedelta(seconds=10) > datetime.datetime.now():
        try:
            _childrens = list(uiautomation.GetRootControl().WindowControl(RegexName='.*?Microsoft.*?Edge').GetChildren())
            if any("打开" in _child.Name for _child in _childrens):
                print(f"提示 : 检测到打开了 【对话框】 上传窗口,正在关闭...!")
                _dialog = uiautomation.GetRootControl().WindowControl(RegexName='.*?Microsoft.*?Edge').WindowControl(Name='打开')
                win32gui.PostMessage(_dialog.NativeWindowHandle, 0x0010, 0, 0)
                break
        except:
            pass


def On_InputPage_UploadDetail_Picture_ByPictureNameStr(driver:WebDriver,PictureStr:list,Delay:float=5):
    
    
    # 1.先打开上传图片对话框
    try:
        
        # 滚动至目标元素
        xpath_value = "//div[@data-type='pic']"
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located(locator=(By.XPATH, xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        print_with_time(f"提示 : 正在滚动至可以打开 【详情页图片对话框】 的元素!")
        
        # 执行点击操作
        try:
            element.click()
        except  (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
        # 验证点击后的界面
        try:
            wait_verify_xpath_path = "//div[contains(@class,'opened')]//iframe"
            WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,wait_verify_xpath_path)))
            print_with_time (f"提示 : 【详情页图片对话框】 已打开!")
        except TimeoutException:
            print_with_time(f"提示 : 未检测到详情页的图片对话框出现!")
            return
            
    except TimeoutException:
        print_with_time(f"提示 : 没有找到打开 【详情页图片对话框】 的元素!")
        return

    # 2.切换进去对话框所在的 iframe
    try:
        xpath_value = "//div[contains(@class,'opened')]//iframe"
        WebDriverWait(driver=driver,timeout=10).until(expected_conditions.frame_to_be_available_and_switch_to_it(locator=(By.XPATH,xpath_value)))
        print_with_time(f"提示 :  切换进入 【详情页图片对话框】 所在的 iframe 元素成功!")
    except TimeoutException:
        print_with_time(f"提示 : 没有找到 【详情页图片对话框】 所在的 iframe 元素选项,无法进行 iframe 切换的操作!")
        return

    # 3.进入对话框的上传界面,出现了 input[@type='file'] 元素
    try:
        
        # 滚动至目标元素
        xpath_value = "//*[text()='本地上传']"
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located(locator=(By.XPATH, xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 执行点击操作
        try:
            element.click()
        except  (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        finally:
            print_with_time(f"提示 : 正在打开可以进行上传图片的页面!")
            close_edge_open_dialog()

        # 验证点击后的界面
        try:
            wait_verify_xpath_path = "//div[contains(@id,'upload')]//input[@type='file' and @multiple and contains(@accept,'image')]"
            WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,wait_verify_xpath_path)))
            print_with_time(f"提示 : 打开可以上传图片的页面成功!")
        except TimeoutException:
            print_with_time(f"提示 : 没有等到可以上传图片的页面!")
            return
            
    except TimeoutException:
        print_with_time(f"提示 : 没有找到可以打开上传图片页面的元素!")
        return

    # 4.对详情图图片进行写入上传
    try:
        
        # 滚动至目标元素
        xpath_value = f"//div[contains(@id,'upload')]//input[@type='file' and @multiple and contains(@accept,'image')]"
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 执行键盘操作
        try:
            element.send_keys(PictureStr)
            # 此处要进行修改,因为上传过程中的界面进行了一个变化,要更改判断条件.
            wait_element_xpath = "//*[contains(text(),'上传中')]"
            element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,wait_element_xpath)))
            print_with_time(f"提示 : 写入上传操作成功,目前正在上传过程中!")
        except TimeoutException:
            print_with_time(f"提示 : 写入上传操作失败!没有等到正在上传的界面!")

        # 验证上传完毕之后的界面
        # try:
        #     wait_element_xpath = f"//input[@type='file']"
        #     # WebDriverWait(driver=driver,timeout=30).until(expected_conditions.invisibility_of_element(element=driver.find_element(by=By.XPATH,value=wait_element_xpath)))
        #     time.sleep(Delay*5)
        #     # print_with_time(f"提示 : 检测到上传完毕的界面!")
            
        # except TimeoutException:
        #     print_with_time(f"提示 : 上传图片文件超时,请进行检测!")
        #     return
        wait_start_time = datetime.datetime.now()
        while wait_start_time + datetime.timedelta(seconds=60) > datetime.datetime.now():
            try:
                driver.find_element(by=By.XPATH,value=f"//*[contains(text(),'个文件上传成功')]")
                print_with_time(f"提示 : 写入上传操作成功,目前已经上完完毕!")
                driver.find_element(by=By.XPATH,value=f"//button/span[text()='完成']").click()
                time.sleep(Delay)
                break
            except NoSuchElementException:
                time.sleep(Delay)

    except TimeoutException:
        print_with_time(f"提示 : 没有找到 {xpath_value} 的元素,无法进行上传图片!")
        return

    # 5.在上传完毕之后,要选择上传的图片
        # 获取所有上传图片的列表
    PictureList = PictureStr.split("\n")
    for index,picture_name in enumerate(PictureList,start=1):
        basename = pathlib.Path(picture_name).absolute().resolve().stem
        suffix = pathlib.Path(picture_name).absolute().resolve().suffix
        ImageSpaceName =  f"{basename}.jpg"
        
        try:
             element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[contains(@class,'PicList_PicturesShow_main-show') and position() <= {PictureList.__len__()} and .//*[contains(text(),'{basename}')]]//input[@type='checkbox']")))
             driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)      
             try:
                 element.click()
                 print_with_time(f"提示  : 点击图片 {ImageSpaceName} 成功!")
                
                
                 if element.get_attribute("aria-checked") != "true":
                    driver.execute_script("arguments[0].click();",element)
                    print_with_time(f"提示 : 点击图片 {ImageSpaceName} 失败!采用 js脚本点击!")
                    print_with_time(f"提示  : 点击图片 {ImageSpaceName} 失败!")
                    
                     
             except  (ElementClickInterceptedException,ElementNotInteractableException):
                  driver.execute_script("arguments[0].click();",element)
                  print_with_time(f"提示 : 点击图片 {ImageSpaceName} 失败!采用 js脚本点击!")
             
                  
        except TimeoutException:
            print_with_time(f"提示 : 没有找到第 {index} 张图片,该图片的文件名为 {ImageSpaceName}")



    # 7.确认选择的图片
    try:
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.visibility_of_element_located((By.XPATH,f"//button/span[contains(text(),'确定') and contains(text(),'{PictureList.__len__()}')]")))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print_with_time(f"提示 : 没有找到 [确定] 的元素选项!")

    driver.switch_to.default_content()
    time.sleep(Delay)



def On_InputPage_UploadDetail_Picture_ByPictureNameList(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,picture_name_list:list,Delay:float=5):
    """批量上传详情页图片.

    Args:
        driver (WebDriver): WebDriver 实例
        wait (WebDriverWait):  WebDriverWait 实例
        actions (ActionChains):  ActionChains 实例
        picture_name_list (list): 图片名称列表,可以是绝对路径,也可以是相对路径
        Delay (float, optional): 延迟时间. Defaults to 5.
    """
    
    # 1.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    
    # 2.调用复用接口进行上传详情页图片
    On_InputPage_UploadDetail_Picture_ByPictureNameStr(driver= driver,wait=wait,actions=actions,PictureStr=picture_list_str,Delay=Delay)
    

    
    

def On_InputPage_UploadDetail_Picture_ByDirectory(driver:WebDriver,picture_directory_path:str,Delay:float=5):
    """批量上传详情页图片.

    Args:
        driver (WebDriver): WebDriver 实例
        wait (WebDriverWait):  WebDriverWait 实例
        actions (ActionChains):  ActionChains 实例
        picture_directory_path (str): 详情页图片所在目录路径,可以是绝对路径,也可以是相对路径
        Delay (float, optional): 延迟时间. Defaults to 5.
    """
    # 1.获取图片列表
    picture_name_list = list()
    for item in pathlib.Path(picture_directory_path).rglob('*'):
        if item.is_file():
            picture_image_path = str(item)
            picture_name_list.append(picture_image_path)
    
    # 2.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    
    # 3.调用复用接口进行上传详情页图片
    On_InputPage_UploadDetail_Picture_ByPictureNameStr(driver= driver,PictureStr=picture_list_str,Delay=Delay)